<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: PHP@妖孽 <dino_ma@163.com>
// +----------------------------------------------------------------------------
/**
 +------------------------------------------------------------------------------
 * 权限模块
 +------------------------------------------------------------------------------
 * @version   1.0
 * @since 2014-8-15
 +------------------------------------------------------------------------------
 */
namespace Admin\Controller;
use Admin\Model\AuthRuleModel;
use Admin\Model\AuthGroupModel;

class AuthController extends AdminController {
	
	/**
	 * @todo 列表
	 */
    public function index(){
    	//$title       =   I('title','strip_tags');
    	$title       =   strip_tags(I('title',''));
    	$map['status']  =   array('egt',0);
    	$map['title']   =   array('like', '%'.(string)$title.'%');
    	$map['module']	=	'admin';
    	$map['type']	=	AuthGroupModel::TYPE_ADMIN;
    	$list = $this->lists('AuthGroup',$map);
    	int_to_string($list);
		$this->assign('_list',$list);
    	$this->meta_title= '权限管理';
    	$this->display();
    }
    
    /**
     * @todo    商户权限列表
     */
    public function merchant(){

        $member_id = (int)I('member_id');
        if($member_id > 0){
            $map['member_id'] = $member_id;
        }
        // 员工列表
        $member = D('Member')->lists(1, 'uid DESC', 'uid,login_name');
        $list = $this->lists(M('auth_merchant'),$map,'create_time desc');
        $this->assign('_list',$list);
        $this->assign('member',$member);
        $this->meta_title= '商户权限';
        $this->display();
    }
    
    /**
     * @todo    添加用户的商户权限
     */
    public function merchantAuth(){
        
        if(IS_POST){
            $merchant = D('Merchant');
            $result = $merchant->merchantUpdate();
            if($result){
                $this->success('设置成功', U('Auth/merchant'));
            }else{
                $this->error($merchant->getError());
            }
        }
        $member_id = (int)I('id');
        $field = 'merchant_id,merchant_name';
        $where['status'] = 1;
        // 员工列表
        $member = D('Member')->lists(1, 'uid DESC', 'uid,login_name');
        // 商户列表
        $merchant_arr = array();
        if($member_id > 0){
            $where['member_id'] = $member_id;
            $merchant_str = M('auth_merchant')->where($where)->getField('rules');
            $merchant_arr = explode(',', $merchant_str);
        }
        
        $list = D('Merchant')->getMerchantList($where, $field, 'merchant_name desc');
        $this->assign('_list', $list);
        $this->assign('member', $member);
        $this->assign('member_id', $member_id);
        $this->assign('merchant_arr', $merchant_arr);
        $this->meta_title= '设置权限';
        $this->display();
    }
    
    /**
     * @todo    修改状态
     */
    public function merchantStatus($method = null){
        if(empty($_REQUEST['id'])) {
            $this->error('请选择要操作的数据!');
        }
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $obj = D('Merchant');
        switch ( strtolower($method) ){
            case 'delete':
                $result = $obj->merchantAuthDel($id);//5:申请核销
                if($result){
                    $this->success('删除成功');
                }else{
                    $this->error($obj->getError());
                }
                break;
            default:
                $this->error($method.'参数非法');
        }
    }
    
    /**
     *@todo 状态修改
     */
    public function changeStatus($method=null){
    	if ( empty($_REQUEST['id']) ) {
    		$this->error('请选择要操作的数据!');
    	}
    	switch ( strtolower($method) ){
    		case 'forbidauthgroup':
    			$this->forbid('AuthGroup');
    			break;
    		case 'resumeauthgroup':
    			$this->resume('AuthGroup');
    			break;
    		case 'deleteauthgroup':
    			$this->delete('AuthGroup');
    			break;
    		default:
    			$this->error($method.'参数非法');
    	}
    }
    
    /**
     * @todo 新增
     */
    public function add(){
    	if(IS_POST){
    		$this->update();
    	}else{
	    	$this->assign('list',null);
	    	$this->meta_title= '添加用户组';
	    	$this->display('edit');
    	}
    }
    
    /**
     * @todo 编辑
     * @param int $id
     */
    public function edit($id = 0){
    	$id &= (int)$id;
    	empty($id) && $this->error('参数错误！');
    	if(IS_POST){
    		$this->update();
    	}else{
			$obj =D('AuthGroup');
	    	$list = $obj->where(array('id'=>$id))->find();
	    	if(empty($list)){
	    		$this->error('没有该用户信息,请不要非法操作!');
	    	}
	    	$this->assign(array('list'=>$list,'pk'=>$obj->getPk()));
	    	$this->meta_title= '编辑用户组';
	    	$this->display('edit');
    	}   	
    }
    
    /**
     *@todo 更新
     */
    private  function update(){
    	$res = D('AuthGroup')->update();
    	if(!$res){
    		$this->error(D('AuthGroup')->getError());
    	}else{
    		$this->success('操作成功', U('Auth/index'));
    	}
    }
    
    /**
     *@todo 将用户添加到用户组
     */
    public function addMmeberToGroup(){
    	$uid            =   (int)I('uid');
    	if(empty($uid) || $uid <=0){
    		$this->error('请不要非法访问');
    	}
    	if(IS_POST){
    		$this->authAddMemberToGroup($uid);
    	}else{
	    	$auth_groups    =   D('AuthGroup')->getGroups();
	    	if(empty($auth_groups)){
	    		$this->error('请先添加用户组,再为用户授权',U('Auth/Index'));
	    	}
	    	$user_groups    =   AuthGroupModel::getUserGroup($uid);
	    	if(!empty($user_groups)){
	    		$ids = array();
	    		foreach($user_groups as $key=>$val){
	    			$ids[]=$val['group_id'];
	    		}
	    		$this->assign('user_groups',arr2str($ids, ','));
	    	}
	    	$login_name     =   D('Member')->getLoginName($uid);
	    	$this->meta_title= '用户组授权';
	    	$this->assign('login_name',   $login_name);
	    	$this->assign('auth_groups',$auth_groups);
	    	$this->display('addMmeberToGroup');
    	}
    }
    
    /**
     * @todo 将用户加入到用户组的实现方法
     * @param string $uid
     */
	private function authAddMemberToGroup($uid){
    	$group_id = I('group_id');
    	$obj_auth_group = D('AuthGroup');
    	if(is_numeric($uid)){
    		if ( is_administrator($uid) ) {
    			$this->error('该用户为超级管理员');
    		}
    		if( !$member_info = M('Member')->where(array('uid'=>$uid))->find() ){
    			$this->error('用户不存在');
    		}else if ($member_info['status']=='-1') {
    			$this->error('用户已被删除');
    		}
    	}
    	if( $group_id && !$obj_auth_group->checkGroupId($group_id)){
    		$this->error($obj_auth_group->getError());
    	}
    	if ( $obj_auth_group->addToGroup($uid,$group_id) ){
    	    // 添加权限组日志记录
    	    action_log('auth_to_group', 'auth', $uid, UID, implode(',', $group_id));
    		$this->success('操作成功');
    	}else{
    		$this->error($obj_auth_group->getError());
    	}
    }
    
    /**
     * @todo 成员授权
     */
    public function user(){
    	if(IS_POST){
    		$uid = I('uid');
    		$this->authAddMemberToGroup($uid);
    	}else{
    		$this->checkGroupId();
//     		$auth_group = M('AuthGroup')->where( array('status'=>array('egt','0'),'module'=>'admin','type'=>AuthGroupModel::TYPE_ADMIN) )->getfield('id,id,title,rules');
    		$prefix   = C('DB_PREFIX');
    		$l_table  = $prefix.(AuthGroupModel::MEMBER);
    		$r_table  = $prefix.(AuthGroupModel::AUTH_GROUP_ACCESS);
    		$model    = M()->table( $l_table.' m' )->join ( $r_table.' a ON m.uid=a.uid' );
    		$_REQUEST = array();
    		$list = $this->lists($model,array('group_id'=>$this->group_id),'m.uid asc','m.uid,m.member_name,m.last_login_time,m.last_login_ip,m.status');
    		int_to_string($list);
    		$this->assign( '_list',     $list );
    		$this->meta_title= '成员授权';
    		$this->display();
    	}
    }
    
    /**
     * @todo 解除授权
     */
    public function removeUserFromGroup(){
    	$uid = (int)I('uid');
    	$group_id = (int)I('group_id');
    	if( $uid==UID ){
    		$this->error('不允许解除自身授权');
    	}
    	if( empty($uid) || empty($group_id) || $uid <= 0 || $group_id <=0){
    		$this->error('参数有误');
    	}
    	$obj_auth_group = D('AuthGroup');
    	if( !$obj_auth_group->find($group_id)){
    		$this->error('用户组不存在');
    	}
    	if ( $obj_auth_group->removeFromGroup($uid,$group_id) ){
    	    // 取消权限组日志记录
    	    action_log('auth_remove_group', 'auth', $uid, UID, $group_id);
    		$this->success('操作成功');
    	}else{
    		$this->error('操作失败');
    	}
    }
    
    /**
     * @todo 检测group_id
     */
    private function checkGroupId(){
    	$group_id = (int)I('group_id');
    	if(empty($group_id) || !is_numeric($group_id)){
    		$this->error('亲,请不要非法访问哦!');
    	}
    	$this->group_id = $group_id;
    }
    
    public function tree($tree = null){
    	$this->assign('tree', $tree);
    	$this->display('tree');
    }
    
    /**
     * @todo 分类授权
     */
    public function category(){
    	if(IS_POST){
    		$cid = I('cid');
    		$gid = I('group_id');
    		if( empty($gid) ){
    			$this->error('参数有误');
    		}
    		$AuthGroup = D('AuthGroup');
    		if( !$AuthGroup->find($gid)){
    			$this->error('用户组不存在');
    		}
    		if( $cid && !$AuthGroup->checkCategoryId($cid)){
    			$this->error($AuthGroup->error);
    		}
    		if ( $AuthGroup->addToCategory($gid,$cid) ){
    			$this->success('操作成功');
    		}else{
    			$this->error('操作失败');
    		}
    	}else{
    		$this->checkGroupId();
    		$group_list     =   D('Category')->getTree();
    		$authed_group   =   AuthGroupModel::getCategoryOfGroup($this->group_id);
    		$this->assign('authed_group',   implode(',',(array)$authed_group));
    		$this->assign('group_list',$group_list);
    		$this->meta_title= '分类授权';
    		$this->display();
    	}
    }
    
    /**
     * 后台节点配置的url作为规则存入auth_rule
     * 执行新节点的插入,已有节点的更新,无效规则的删除三项任务
     */
    public function updateRules(){
    	//需要新增的节点必然位于$nodes
    	$nodes    = $this->returnNodes(false);
    
    	$AuthRule = M('AuthRule');
    	$map      = array('module'=>'admin','type'=>array('in','1,2'));//status全部取出,以进行更新
    	//需要更新和删除的节点必然位于$rules
    	$rules    = $AuthRule->where($map)->order('name')->select();
    
    	//构建insert数据
    	$data     = array();//保存需要插入和更新的新节点
    	if(!empty($nodes)){
	    	foreach ($nodes as $value){
	    		$temp['id']   = $value['id'];
	    		$temp['name']   = $value['url'];
	    		$temp['title']  = $value['title'];
	    		$temp['module'] = 'admin';
	    		/* if($value['pid'] >0){
	    			$temp['type'] = AuthRuleModel::RULE_URL;
	    		}else{
	    			$temp['type'] = AuthRuleModel::RULE_MAIN;
	    		} */
	    		//暂时只考虑节点
	    		$temp['type'] = AuthRuleModel::RULE_URL;
	    		$temp['status']   = 1;
	    		$data[strtolower($temp['id'].$temp['name'].$temp['module'].$temp['type'])] = $temp;//去除重复项
	    	}
    	}
    	$update = array();//保存需要更新的节点
    	$ids    = array();//保存需要删除的节点的id
    	if(!empty($rules)){
	    	foreach ($rules as $index=>$rule){
	    		$key = strtolower($rule['id'].$rule['name'].$rule['module'].$rule['type']);
	    		if ( isset($data[$key]) ) {//如果数据库中的规则与配置的节点匹配,说明是需要更新的节点
	    			$data[$key]['id'] = $rule['id'];//为需要更新的节点补充id值
	    			$update[] = $data[$key];
	    			unset($data[$key]);
	    			unset($rules[$index]);
	    			unset($rule['condition']);
	    			$diff[$rule['id']]=$rule;
	    		}elseif($rule['status']==1){
	    			$ids[] = $rule['id'];
	    		}
	    	}
    	}
    	if ( count($update) ) {
    		foreach ($update as $k=>$row){
    			if ( $row!=$diff[$row['id']] ) {
    				$AuthRule->where(array('id'=>$row['id']))->save($row);
    			}
    		}
    	}
    	if ( count($ids) ) {
    		$AuthRule->where( array( 'id'=>array('IN',implode(',',$ids)) ) )->save(array('status'=>-1));
    		//删除规则是否需要从每个用户组的访问授权表中移除该规则?
    	}
    	if( count($data) ){
    		$AuthRule->insertIgnoreAddAll(array_values($data));
    	}
    	if ( $AuthRule->getDbError() ) {
    		trace('['.__METHOD__.']:'.$AuthRule->getDbError());
    		return false;
    	}else{
    		return true;
    	}
    }
    
    /**
     * @todo 访问授权
     */
    public function auth(){
    	if(IS_POST){
    		if(isset($_POST['rules'])){
    			sort($_POST['rules']);
    			$_POST['rules']  = implode( ',' , array_unique($_POST['rules']));
    		}else{
    			$_POST['rules'] ='';
    		}
    	
    		$_POST['module'] =  'admin';
    		$_POST['type']   =  AuthGroupModel::TYPE_ADMIN;
    		$AuthGroup       =  D('AuthGroup');
    		$data = $AuthGroup->create();
    		if ( $data ) {
    			if ( empty($data['id']) ) {
    				$r = $AuthGroup->add();
    			}else{
    				$r = $AuthGroup->save();
    			}
    			if($r===false){
    				$this->error('操作失败'.$AuthGroup->getError());
    			} else{
    				$this->success('操作成功!',U('index'));
    			}
    		}else{
    			$this->error('操作失败'.$AuthGroup->getError());
    		}
    	}else{
    		$this->checkGroupId();
    		$this->updateRules();
    		$auth_group = M('AuthGroup')->where( array('status'=>array('egt','0'),'module'=>'admin','type'=>AuthGroupModel::TYPE_ADMIN) )
    		->getfield('id,id,title,rules');
    		$node_list   = $this->returnNodes();
    		$map         = array('module'=>'admin','type'=>AuthRuleModel::RULE_MAIN,'status'=>1);
    		$main_rules  = M('AuthRule')->where($map)->getField('name,id');
    		$map         = array('module'=>'admin','type'=>AuthRuleModel::RULE_URL,'status'=>1);
    		$child_rules = M('AuthRule')->where($map)->getField('name,id');
    		$this->assign('main_rules', $main_rules);
    		$this->assign('auth_rules', $child_rules);
    		$this->assign('node_list',  $node_list);
    		$this->assign('auth_group', $auth_group);
    		$this->assign('this_group', $auth_group[$this->group_id]);
    		$this->meta_title= '访问授权';
    		$this->display();
    	}
    }
    
    /**
     * @todo 部门管理
     */
    public function department(){
    	$tree = D('AuthGroup')->getTree(0,'id,department_name,sort,father_id,status');
    	$this->assign('tree', $tree);
    	C('_SYS_GET_DEPARTMENT_TREE_', true); //标记获取部门树模板
    	$this->assign('meta_title','部门管理');
    	$this->display('department');
    }
    
    
    /**
     * 显示部门树，仅支持内部调
     * @param  array $tree 分类树
     */
    public function departmentTree($tree = null){
    	C('_SYS_GET_DEPARTMENT_TREE_') || $this->_empty();
    	$this->assign('tree', $tree);
    	$this->display('Auth:departmentTree');
    }
    
    /**
     * @todo 创建部门
     */
    public function departmentAdd(){
		if(IS_POST){
			$obj = D('AuthDepartment');
			$return = $obj->update();
			if(!$return){
				$this->error($obj->getError());
			}else{
				$this->success('操作成功！',U('department'));
			}
		}else{
			$this->getFatherInfo();
			$this->assign('meta_title','部门管理');
			$this->assign('meta_title_c','创建部门');
			$this->display('departmentEdit');
		}
    }
    
    /**
     * @todo 获取上级部门
     */
    private function getFatherInfo(){
    	$father_id = (int)I('father_id');
    	if($father_id !=0){
    		$father_info = M('AuthDepartment')->field('id,department_name')->where(array('id'=>$father_id))->find();
    	}else{
    		$father_info = array('id'=>0,'department_name'=>'无');
    	}
    	$this->assign('father_info',$father_info);
    }
    
    /**
     * @todo 更新部门
     */
    public function departmentEdit(){
    	$id = (int)I('id');
    	if($id =='0'){
    		$this->error('参数错误!');
    	}
    	if(IS_POST){
    		$obj = D('AuthDepartment');
    		$return = $obj->update();
    		if(!$return){
    			$this->error($obj->getError());
    		}else{
    			$this->success('操作成功！',U('department'));
    		}
    	}else{
    		$info = M('AuthDepartment')->where(array('id'=>$id))->find();
    		$this->getFatherInfo();
    		$this->assign('meta_title','部门管理');
    		$this->assign('meta_title_c','更新部门');
    		$this->assign('info',$info);
    		$this->display('departmentEdit');
    	}
    }
    
    
    /**
     *@todo 删除一个部门
     */
    public function departmentRemove(){
    	$department_id = (int)I('id');
    	if(empty($department_id) || $department_id == '0'){
    		$this->error('参数错误!');
    	}
    	$obj = M('AuthDepartment');
    	//判断该分类下有没有子部门，有则不允许删除
    	$child = $obj->where(array('father_id'=>$department_id,'status'=>array('gt',-1)))->field('id')->find();
    	if(!empty($child)){
    		$this->error('请先删除该部门下的子部门');
    	}
    	//判断该部门下有没有员工
    	$member_list = M('AuthDepartmentMember')->where(array('department_id'=>$department_id))->field('department_id')->find();
    	if(!empty($member_list)){
    		$this->error('请先删除该部门下的员工');
    	}
    	//删除该部门 信息
    	$res = $this->delete ( $obj , array('id'=>$department_id));
    	if($res !== false){
    		$this->success('删除部门成功！');
    	}else{
    		$this->error('删除部门失败！');
    	}
    }
    
    
    
    /**
     * @todo 部门下的小组列表
     */
    public function team($department_id){
    	$department_id = (int)$department_id;
    	if($department_id==0){
    		$this->error('请求参数有误.~');
    	}
    	$list = $this->lists('AuthTeam',array('department_id'=>$department_id,'status'=>1),'`team_id` desc');
    	$this->meta_title= '小组列表';
    	$this->assign('_list',$list);
    	$this->display('team');
    }
    
    /**
     *@todo 删除一个组
     */
    public function teamRemove(){
    	$team_id = I('id');
    	if(empty($team_id) || $team_id == '0'){
    		$this->error('参数错误!');
    	}
    	//判断该小组下有没有员工
    	$member_list = M('AuthTeamMember')->where(array('team_id'=>$team_id))->field('department_id')->find();
    	if(!empty($member_list)){
    		$this->error('请先删除该部门下的员工');
    	}
    	//删除该小组 信息
    	action_log('delete_team', 'team', $team_id, UID);//fang update
    	$res = $this->delete (M('AuthTeam'), array('team_id'=>$team_id));
    	if($res !== false){
    		$this->success('删除小组成功！');
    	}else{
    		$this->error('删除小组失败！');
    	}
    }
    
    
    /**
     * @todo 创建组
     */
    public function addTeam(){
    	$department_id = (int)I('department_id');
    	if($department_id==0){
    		$this->error('请求参数有误.~');
    	}
    	if(IS_POST){
    		$this->teamUpdate();
    	}else{
    		$this->meta_title= '创建组';
    		$this->assign('list',null);
    		$this->display('editTeam');
    	}
    }
    
    /**
     * @todo 编辑组
     */
    public function editTeam(){
//     	$department_id = (int)I('department_id');
//     	if($department_id==0){
//     		$this->error('请求参数有误.~');
//     	}
    	$id = (int)I('team_id');
    	if($id == 0){
    		$this->error('请求参数有误');
    	}
    	if(IS_POST){
    		$this->teamUpdate();
    	}else {
    		$obj =M('AuthTeam');
    		$list = $obj->where(array('team_id'=>$id))->find();
    		$this->assign(array('list'=>$list));
    		$this->meta_title= '编辑组';
    		$this->display('editTeam');
    	}
    }
    
    /**
     * @todo 增加/更新组实现
     */
    private function teamUpdate(){
    	$obj = D('AuthTeam');
    	$res = $obj->update();
    	if(!$res){
    		$this->error($obj->getError());
    	}else{
    	    //fang update
    	    $team_id = (int)I('team_id', 0);
    	    if($team_id){
    	        action_log('team_edit', 'team', $res, UID);
    	    }else{
    	        action_log('team_add', 'team', $res, UID);
    	    }
    		S('service_get_department_team_member_list',null);//更新缓存
    		$this->success('操作成功',U('Auth/team',array('department_id'=>I('department_id'))));
    	}
    }
    
    /**
     * @todo 小组成员授权
     */
    public function teamMember(){
    	$team_id = (int)I('team_id');
    	if(empty($team_id) || !is_numeric($team_id)){
    		$this->error('亲,请不要非法访问哦!');
    	}
    	$department_id = getDepartmenIdByTeamId($team_id);
    	if(IS_POST){
    		$uid = I('uid');
    		$obj_auth_group = D('AuthGroup');
    		if(is_numeric($uid)){
    			if ( is_administrator($uid) ) {
    				$this->error('该用户为超级管理员');
    			}
    			if( !$member_info = M('Member')->where(array('uid'=>$uid))->find() ){
    				$this->error('用户不存在');
    			}else if ($member_info['status']=='-1') {
    				$this->error('用户已被删除');
    			}
    		}
    		if( $team_id && !$obj_auth_group->checkId(M('AuthTeam'),$team_id)){
    			$this->error($obj_auth_group->getError());
    		}
    		$obj =D('AuthTeam');
    		if ( $obj->addToTeam($uid,$team_id,$department_id) ){
    			S('service_get_department_team_member_list',null);//更新缓存
    			$this->success('操作成功');
    		}else{
    			$this->error($obj->getError());
    		}
    	}else{
    		$prefix   = C('DB_PREFIX');
    		$l_table  = $prefix.(AuthGroupModel::MEMBER);
    		$r_table  = $prefix.('auth_team_member');
    		$model    = M()->table( $l_table.' m' )->join ('join '. $r_table.' a ON m.uid=a.member_id' );
    		$_REQUEST = array();
    		$list = $this->lists($model,array('a.team_id'=>$team_id),'m.uid asc','m.uid,m.login_name,m.last_login_time,m.last_login_ip,m.status');
    		int_to_string($list);
    		$this->assign('department_id',$department_id);
    		$this->assign( '_list',     $list );
    		$this->meta_title= '小组成员授权';
    		$this->display('teamMember');
    	}
    }
    
    
    /**
     * @todo 开除小组员工
     */
    public function removeUserFromTeam(){
    	$member_id = (int)I('member_id');
    	$team_id = (int)I('team_id');
    	if( $member_id==UID ){
    		$this->error('不允许解除自身授权');
    	}
    	if( empty($member_id) || empty($team_id) || $member_id <= 0 || $team_id <=0){
    		$this->error('参数有误');
    	}
    	$obj = D('AuthTeam');
    	if( !$obj->where(array('team_id'=>$team_id))->find()){
    		$this->error('小组不存在');
    	}
    	if ( $obj->removeUserFromDepart($member_id,$team_id) ){
    		S('service_get_department_team_member_list',null);//更新缓存
    		action_log('remove_user', 'team', $team_id, UID);
    		$this->success('操作成功');
    	}else{
    		$this->error('操作失败');
    	}
    }
    
    
    
}